package com.example.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Description:
 * User: 故我
 * Date: 2023-11-15
 * Time: 11:05
 */
@RestController
public class UserController {
    private String SESSION_KEY = "SESSION_KEY";

    /**
     * 将 session 存储到 redis 中
     */
    @RequestMapping("/login")
    public String login(HttpSession session) {
        // 设置session
        String username = "zhangsan";
        session.setAttribute(SESSION_KEY, username);
        return "set session success";
    }

    /**
     *  从 redis 中 获取 session 信息
     */
    @RequestMapping("/userinfo")
    public String getSession(HttpServletRequest request){
        String user = null;
        HttpSession session = request.getSession(false);
        if(session != null){
            Object object = session.getAttribute(SESSION_KEY);
            if(object != null){
                user = object.toString();
            }
        }
        return user;
    }

}
